package com.base.common.converter;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.model.SelectItem;

import org.operamasks.faces.annotation.DefineConverter;

@DefineConverter(id = "modulesConverter")
public class ModulesConverter implements Converter {
	private static Map modulesMap = new HashMap<String, String>();
	static {
		modulesMap.put("system", "系统管理");
		modulesMap.put("home", "系统首页");
		modulesMap.put("portal", "个人首页");
	}

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
		return null;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
		if (arg2 != null) {
			String modules = arg2.toString();
			StringBuilder names = new StringBuilder();
			String[] temp = modules.split(",");
			for (int i = 0; i < temp.length; i++) {
				if (i > 0)
					names.append(",");
				if (modulesMap.containsKey(temp[i])) {
					names.append(modulesMap.get(temp[i]));
				}
			}
			return names.toString();
		}
		return null;
	}

	public static SelectItem[] getModulesItems() {
		int i = 0;
		SelectItem[] result = new SelectItem[modulesMap.size()];
		Set<String> keys = modulesMap.keySet();
		Iterator it = keys.iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			String value = (String) modulesMap.get(key);
			result[i] = new SelectItem(key, value);
			i++;
		}
		return result;
	}
}
